<template>
  <div class="uploadComponent">
    <el-upload
      class="upload-demo"
      ref="upload"
      action="/d_api/utils/uploadfiles"
      :auto-upload="false"
      list-type="text"
      :show-file-list="false"
      :accept="acceptTpye"
      :multiple="false"
      :before-upload="handelBeforeupload"
      :on-error="handelError"
      :on-success="handelSucess"
      :on-change="handelChange"
      :on-remove="handelRemove"
      :disabled="(!isMyCaeate && !isOtherDesiger) || !canEdit"
    >
      <div
        class="uplaodControll"
        :class="{ 'is-disabled': (!isMyCaeate && !isOtherDesiger) || !canEdit }"
        v-if="
          (!currData.iconPath && uploadComponentName == 'cover') ||
          (!currData.guidePath && uploadComponentName == 'file')
        "
      >
        <div class="iconBox">
          <img :src="require('@/assets/images/naddIcon.png')" />
        </div>
        <div class="tips">{{ tips }}</div>
      </div>
      <div
        class="fileListBox"
        :class="{ 'is-disabled': (!isMyCaeate && !isOtherDesiger) || !canEdit }"
        v-else
      >
        <div class="imgFileBox" v-if="uploadComponentName == 'cover'">
          <img :src="filterIMGUrl" />
        </div>
        <div class="fileBox" v-if="uploadComponentName == 'file'">
          <div
            v-for="(item, index) in fileList"
            :key="index"
            @click.stop="handelShowFile(item)"
          >
            {{ item | filterName }}
          </div>
        </div>
      </div>
    </el-upload>
    <previewImgVidoeFile
      :showPerview="amplify"
      @close="handelclose"
      :showData="amplifyFile"
      :fileList="fileList"
    />
  </div>
</template>

<script>
// 导入sheet.js依赖
import { d_uploadmultifiles, uploadfile, upload } from "@/request/upload";
import { debounce, location } from "@/util/tool";
import { mapState } from "vuex";
import previewImgVidoeFile from "@/components/previewImgVidoeFile/previewImgVidoeFile";
import { encryptionToString } from "@/util/qetag";
import { notUploadFileType } from "@/util/uploadConfig";

export default {
  components: {
    previewImgVidoeFile,
  },
  data() {
    return {
      fileList: [], // 已上传的文件路径
      amplify: false, // dialog查看已上传文件详情
      amplifyFile: {}, // 点击已上传的文件数据
      timer: null, // 计时器
      location: location(window),
    };
  },
  props: {
    acceptTpye: String, // 接受文件类型
    tips: String, // 上传图标下的文字提示
    uploadComponentName: String, // 当前组件自定义名字
    currData: Object, // 当前展示的数据
    isMyCaeate: Boolean, // 是否自己设计的
    isOtherDesiger: Boolean, // 是否是其它课程设计师
    canEdit: Boolean, // 当前课程状态可否编辑
  },
  watch: {
    taskCommitJson(n, o) {},
    currData(n, io) {
      if (
        this.uploadComponentName == "file" &&
        this.currData.guidePath !== ""
      ) {
        this.fileList = this.currData.guidePath.split(";");
      }
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    filterIMGUrl() {
      return this.currData.iconPath;
      // let url = this.currData.iconPath;
      // return url.split(url.substring(url.lastIndexOf("&")))[0];
    },
  },
  filters: {
    filterName(str) {
      return str.substring(str.lastIndexOf("&") + 1);
    },
  },
  created() {
    if (this.uploadComponentName == "file" && this.currData.guidePath !== "") {
      this.fileList = this.currData?.guidePath?.split(";");
    }
  },
  methods: {
    // 展示文件
    handelShowFile(item) {
      if ((!this.isMyCaeate && !this.isOtherDesiger) || !this.canEdit) return;
      this.amplifyFile = this.urlFormat(item);
      if (this.amplifyFile.type == "zip" || this.amplifyFile.type == "rar") {
        window.open(this.amplifyFile.url);
        return;
      }
      this.amplify = true;
    },
    // url数据格式化
    urlFormat(url) {
      return {
        type: url.substring(url.lastIndexOf(".") + 1),
        name: url.substring(url.lastIndexOf("/") + 1),
        url: url.substring(0, url.lastIndexOf("&")),
      };
    },
    // 关闭预览文文件窗口
    handelclose() {
      this.amplify = false;
    },
    // 打开文件 上传
    openFile() {
      this.$refs.upload.$children[0].$refs.input.click();
    },
    // 上传成功
    handelSucess(response, file, fileList) {
      this.$message({
        message: "上传成功",
        type: "success",
      });
    },
    // 上传失败
    handelError(err, file, fileList) {
      if (file.raw.size > 1000000000) {
        this.$message({
          message: "文件大小不能超过1Gb",
          type: "error",
        });
      }
    },
    // 文件改变
    handelChange(file, fileList) {
      if (file.raw.size > 1000000000) {
        this.$antdMessage.error({
          content: "文件大小不能超过1Gb",
        });
        return;
      }
      if (file.status == "ready") {
        // 判断用户是否登录
        // if (!this.$store.commit("user/checkUserIslogin", this)) return;

        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }

        this.timer = this.timeOutUpload();
      }
    },
    // 节流判断 upload组件 需要上传的文件 onchange是否已经结束
    timeOutUpload() {
      return setTimeout(() => {
        this.uploadFiles();
        clearTimeout(this.timer);
      }, 100);
    },
    // 上传文件
    async uploadFiles() {
      if (!this.userInfo.accessToken) {
        this.$router.push({
          name: "Login",
        });
        return;
      }
      let files = this.$refs.upload.uploadFiles;
      let uploadForm = new FormData();
      let hashArray = [];
      for (let item of files) {
        // 检查文件类型
        const uLoadFileType = notUploadFileType;
        if (
          uLoadFileType.indexOf(item.type) !== -1 || uLoadFileType.indexOf(item.name.substring(item.name.lastIndexOf("."))) !== -1) {
          this.$antdMessage.error({
            content: "此类型文件无法上传！",
          });
          return;
        }

        // 检查文件大小
        if (item.size > 1000000000) {
          this.$antdMessage.error({
            content: "上传文件最大为1Gb！",
          });
          return;
        }

        // 文件名
        let fileName = item.name;
        // 过滤英文分号
        if (item.name.indexOf(";") !== -1) {
          fileName = item.name.replace(/;/g, "；");
        }

        let hash = await encryptionToString(item);
        if (hash === "Fto5o-5ea0sNMlW_75VgGJCv2AcJ") {
          this.$antdMessage.error({
            content: "文件读取错误！",
          });
          return;
        }
        if (hash) hashArray.push(hash);

        // 校验通过的文件会放入formData内等待上传
        uploadForm.append("file", item.raw, fileName);
      }

      uploadForm.append(
        "courseInfo",
        JSON.stringify({
          userID: this.userInfo.userID,
          FileHashArray: JSON.stringify(hashArray), // 文件内容hash
        })
      );

      d_uploadmultifiles(uploadForm)
        .then((res) => {
          if (!res.data.filePaths.length) {
            this.$antdMessage.error({
              content: "上传失败",
            });
            return;
          }
          if (res.errno === 0) {
            // let fileUrl = res.split("上传成功！文件地址分别为：")[1];
            let fileUrl = res.data.filePaths;
            if (fileUrl) {
              fileUrl.forEach((item) => {
                if (this.uploadComponentName == "cover") {
                  this.fileList = {
                    type: item.substring(item.lastIndexOf(".") + 1),
                    name: item.substring(item.lastIndexOf("/") + 1),
                    url:
                      this.location + item.substring(0, item.lastIndexOf("&")),
                  };
                  // this.pushFileUrlToFileList(fileUrl)
                }
                if (this.uploadComponentName == "file") {
                  // this.fileList.push(this.urlFormatUploadData(fileUrl))
                  this.pushFileUrlToFileList(this.location + item);
                }
                this.$emit(
                  "uploadDataChange",
                  this.fileList,
                  this.uploadComponentName
                );
              });
            }
          } else {
            this.$antdMessage.error({
              content: "上传失败！",
            });
          }
        })
        .catch((err) => console.log(err));
      // 清除文件列表中的文件
      this.$refs.upload.clearFiles();
    },
    pushFileUrlToFileList(urlStr) {
      // 单文件
      this.fileList = [urlStr];
    },
    // 移除文件
    handelRemove(file, fileList) {
      const nFileList = this.fileList.filter((item) => item.name != file.name);
      this.fileList = nFileList;
    },
    // 格式化上传的url数据
    urlFormatUploadData(url) {
      return {
        type: url.substring(url.lastIndexOf(".") + 1),
        name: url.substring(url.lastIndexOf("/") + 1),
        url: url,
      };
    },
  },
};
</script>


<style lang="stylus" >
.uploadComponent {
  width: 100%;
  height: 100%;

  .upload-demo {
    width: 100%;
    height: 100%;

    .uplaodControll {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      border: solid 1px #707070;

      .iconBox {
        img {
          object-fit: cover;
        }
      }

      .tips {
        font-family: MingLiU-ExtB;
        font-size: 16px;
        letter-spacing: 0px;
        color: rgba(165, 161, 161, 0.5);
      }
    }

    .fileListBox {
      .imgFileBox {
        width: 100%;
        height: 100%;

        img {
          object-fit: cover;
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>